package com.njtoyo.taxi.admin.library.payment.cmb;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.njtoyo.taxi.admin.library.payment.cmb.config.CmbPayConfigTest;
import com.njtoyo.taxi.admin.library.payment.cmb.config.CmbPayConfig;
import com.njtoyo.taxi.admin.library.payment.cmb.file.http.ContentType;
import com.njtoyo.taxi.admin.library.payment.cmb.file.http.HttpClient;
import com.njtoyo.taxi.admin.library.payment.cmb.file.http.HttpMethod;
import com.njtoyo.taxi.admin.library.payment.cmb.file.http.RequestConfig;
import com.njtoyo.taxi.admin.library.payment.cmb.notify.SM2Util;
import com.njtoyo.taxi.admin.library.payment.cmb.pojo.CmbBillDownload;
import com.njtoyo.taxi.admin.library.payment.cmb.pojo.CmbPayConfigEntity;
import com.njtoyo.taxi.admin.library.payment.cmb.sign.CmbUtils;
import com.njtoyo.taxi.admin.library.payment.cmb.sign.MD5Utils;
import com.njtoyo.taxi.admin.library.payment.cmb.sign.SignatureUtil;
import com.njtoyo.taxi.admin.library.payment.common.CmbRefundInfo;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.*;

@Slf4j
public class CmbPayClient {


    /**
     * 申请文件上传接口
     *
     * @param batchNo  批次号 唯一    格式为当日日期yyyyMMdd+3位数字或大写字母，如2022072101A
     * @param fileFdc  文件摘要
     * @param totalCnt 文件总笔数
     * @param totalAmt 文件总金额
     */
    public static Map<String, Object> fileUploadApply(String batchNo, String fileFdc, String totalCnt, String totalAmt) {
        CmbPayConfigEntity envConfig = getEnvConfig();
        String suffix = "/midsrv/v2/nts";
        if (envConfig.getIsProd()) {
            suffix = "/midsrv/ntsv2";
        }
        String requestUrl = envConfig.getRequestUrl() + suffix + "/fileUploadApply";
        String fileType = "AP";
        String encAlg = "NONE";
        String fdcAlg = "MD5";
        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();


        Map<String, String> requestParamsBody = new HashMap<>();
        requestParamsBody.put("batchNo", batchNo);
        requestParamsBody.put("platformNo", envConfig.getMchId());
        requestParamsBody.put("fileFdc", fileFdc);
        requestParamsBody.put("totalCnt", totalCnt);
        requestParamsBody.put("totalAmt", totalAmt);
        requestParamsBody.put("fileType", fileType);
        requestParamsBody.put("encAlg", encAlg);
        requestParamsBody.put("fdcAlg", fdcAlg);
        requestParamsBody.put("fundSrc", envConfig.getSubStoreId());
        System.out.println("requestParamsBody" + requestParamsBody);


        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("分账请求头加签出现错误:{}", e.getMessage());
        }
        System.out.println("headers" + headersPost);
        Map<String, Object> result = HttpClient.request(requestUrl, HttpMethod.POST, headersPost, bizPostParams, envConfig.getPublicKey());
        log.info("请求文件上传申请接口:{}", result);

        return result;
    }


    /**
     * 上传转账文件
     *
     * @param submitUrl 文件上传地址
     * @param csvFile   本地文件的地址
     */
    public static boolean fileUpload(String submitUrl, String csvFile) {
        boolean result = HttpClient.uploadFile(submitUrl, new File(csvFile), ContentType.ZIP);
        log.info("转账文件上传结果:{}", result);
        return result;
    }


    /**
     * 文件提交
     *
     * @param batchNo 批次号
     */
    public static Map<String, Object> fileSubmit(String batchNo) {
        CmbPayConfigEntity envConfig = getEnvConfig();
        String suffix = "/midsrv/v2/nts";
        if (envConfig.getIsProd()) {
            suffix = "/midsrv/ntsv2";
        }
        String requestUrl = envConfig.getRequestUrl() + suffix + "/fileSubmit";

        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        Map<String, String> requestParamsBody = new HashMap<>();
        requestParamsBody.put("batchNo", batchNo);
        requestParamsBody.put("platformNo", envConfig.getMchId());
        requestParamsBody.put("fileType", "AP");

        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("提交文件上传请求头加签出现错误:{}", e.getMessage());
        }
        Map<String, Object> result = HttpClient.request(requestUrl, HttpMethod.POST, headersPost, bizPostParams, envConfig.getPublicKey());
        log.info("提交文件上传接口返回结果:{}", result);
        return result;
    }

    public static String allTypeBillDownloadUrl(String billDate) throws Exception {
        String requestUrl = "https://api.cmbchina.com/midsrv/ntsv2/reconFileDownload";
        CmbPayConfigEntity envConfig = getEnvConfig();
        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        Map<String, String> requestParamsBody = new HashMap<>();
        requestParamsBody.put("clearDate", billDate);
        requestParamsBody.put("platformNo", envConfig.getMchId());
        System.out.println("requestParamsBody" + requestParamsBody);

        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("分账请求头加签出现错误:{}", e.getMessage());
        }
        System.out.println("headers" + headersPost);
        String result = HttpRequest.get(requestUrl).addHeaders(headersPost).formStr(requestParamsBody).execute().body();
        log.info("请求文件上传申请接口:{}", result);
        return null;
    }


    /**
     * 交易对账单下载
     */
    public static String billDownloadUrl(CmbBillDownload cmbBillDownload) throws Exception {
        CmbPayConfigEntity envConfig = getEnvConfig();
        String requestUrl = envConfig.getRequestUrl() + "/bill/check/adapter";
        Map<String, Object> params = BeanUtil.beanToMap(cmbBillDownload, false, true);
        Map<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("requestBody", params);

        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        String bizPostParams = JSON.toJSONString(params);
        Map<String, String> headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        headersPost.put("verify", "SM3withSM2");
        headersPost.put("channel", "AP");
        headersPost.put("funcCode", "BILLRECORD_GET_FORAPI");
        headersPost.put("sysCode", "AP");
        Map<String, Object> requestResult = HttpClient.request(requestUrl, HttpMethod.POST, headersPost, JSON.toJSONString(requestBodyMap), envConfig.getPublicKey());
        log.info("请求结果：{}", requestResult);
        String downloadUrl = "";
        if (ObjectUtil.isNotNull(requestResult.get("code")) && ObjectUtil.equal(requestResult.get("code"), "SUC000000")) {
            JSONObject jsonObject = (JSONObject) requestResult.get("data");
            downloadUrl = jsonObject.getString("downloadUrl");
        }
        return downloadUrl;

    }


    /**
     * 批次处理结果查询接口
     */
    public static Map<String, Object> fileBatchQry(String batchNo) {
        log.info("===========执行批次[{}]处理结果查询============", batchNo);
        CmbPayConfigEntity envConfig = getEnvConfig();
        String suffix = "/midsrv/v2/nts";
        if (envConfig.getIsProd()) {
            suffix = "/midsrv/ntsv2";
        }
        String requestUrl = envConfig.getRequestUrl() + suffix + "/fileBatchQry";
        log.info("批次[{}]处理结果查询请求url:{}", batchNo, requestUrl);
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        Map<String, Object> requestParamsBody = new HashMap<>();
        requestParamsBody.put("batchNo", batchNo);
        requestParamsBody.put("platformNo", envConfig.getMchId());
        requestParamsBody.put("fileType", "AP");

        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("提交文件上传请求头加签出现错误:{}", e.getMessage());
        }
        log.info("批次[{}]处理结果查询请求头参数:{}", batchNo, JSON.toJSONString(headersPost));
        log.info("批次[{}]处理结果查询请求体参数:{}", batchNo, JSON.toJSONString(requestParamsBody));
        String result = HttpRequest.get(requestUrl).addHeaders(headersPost).form(requestParamsBody).execute().body();
        log.info("批次处理结果查询返回结果:{}", result);
        log.info("===========执行批次处理结果查询结束============");
        return JSON.parseObject(result);
    }


    /**
     * 退款接口
     *
     * @return
     */
    public static Map<String, String> refund(CmbRefundInfo cmbRefundInfo) {
        log.info("执行退款操作");
        String requestUrl = "https://api.cmbchina.com/ptn/api/weixinPay/refund";
        CmbPayConfigEntity envConfig = getEnvConfig();
        cmbRefundInfo.setMerId(envConfig.getMchId());
        cmbRefundInfo.setUserId(envConfig.getUserId());
        cmbRefundInfo.setSubMerId(envConfig.getSubMerId());
        cmbRefundInfo.setSubStoreId(envConfig.getSubStoreId());
        Map<String, Object> params = BeanUtil.beanToMap(cmbRefundInfo, false, true);
        Map<String, String> refundResult = sendRequest(requestUrl, params);
        return refundResult;
    }

    /**
     * 退款接口
     *
     * @param orderId        商户端生成退款订单号，要求此订单号母单商户下唯一
     * @param origOrderId    原交易的母单商户订单号
     * @param refundReason   退款原因
     * @param txnAmt         原交易金额，单位为分(如果是合单交易填写合单交易的交易金额)
     * @param refundAmt      退款金额，单位为分
     * @param subOrigOrderId 子单对应的原子单商户订单号
     * @param subOrderId     退款商户订单号，在该子单商户下唯一
     * @return
     */
    public static Map<String, String> refund(String orderId, String origOrderId, String refundReason,
                                             String subOrigOrderId, String subOrderId,
                                             String txnAmt, String refundAmt) {
        log.info("执行退款操作");
        String requestUrl = "https://api.cmbchina.com/ptn/api/weixinPay/refund";
        CmbPayConfigEntity envConfig = getEnvConfig();
        Map<String, Object> params = new HashMap<>();
        params.put("merId", envConfig.getMchId());
        params.put("origOrderId", origOrderId);
        params.put("orderId", orderId);
        params.put("userId", envConfig.getUserId());
        params.put("subMerId", envConfig.getSubMerId());
        params.put("subStoreId", envConfig.getSubStoreId());
        params.put("subOrigOrderId", subOrigOrderId);
        params.put("subOrderId", subOrderId);
        params.put("txnAmt", txnAmt);
        params.put("refundAmt", refundAmt);
        Map<String, String> refundResult = sendRequest(requestUrl, params);

        System.out.println(refundResult);
        return refundResult;
    }


    public static Map<String, String> orderStatusQuery(String orderId) {
        String requestUrl = "https://api.cmbchina.com/ptn/api/weixinPay/orderStatusQuery";
        CmbPayConfigEntity envConfig = getEnvConfig();
        Map<String, Object> params = new HashMap<>();
        params.put("merId", envConfig.getMchId());
        params.put("orderId", orderId);
        params.put("userId", envConfig.getUserId());
        Map<String, String> refundResult = sendRequest(requestUrl, params);

        System.out.println("***********" + refundResult);
        return refundResult;
    }


    public static String mbrBalQry() {
        String requestUrl = "https://api.cmbchina.com/midsrv/ntsv2/mbrBalQry";

        CmbPayConfigEntity envConfig = getEnvConfig();
        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        Map<String, String> requestParamsBody = new HashMap<>();
        requestParamsBody.put("platformNo", CmbPayConfig.mch_id);
        requestParamsBody.put("mbrNo", "30899914121002R0001");
        System.out.println("requestParamsBody" + requestParamsBody);

        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("余额查询请求头加签出现错误:{}", e.getMessage());
        }
        System.out.println("headers" + headersPost);
        String result = HttpRequest.get(requestUrl).addHeaders(headersPost).formStr(requestParamsBody).execute().body();
        log.info("余额查询接口:{}", result);

        return result;
    }


    /**
     * 代发回执单下载
     *
     * @param origRespNo
     * @return
     */
    public static String receiptFileDownload(String origRespNo) {
        String requestUrl = "https://api.cmbchina.com/midsrv/ntsv2/receiptFileDownload";

        CmbPayConfigEntity envConfig = getEnvConfig();
        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        Map<String, String> requestParamsBody = new HashMap<>();
        requestParamsBody.put("platformNo", CmbPayConfig.mch_id);
        requestParamsBody.put("origRespNo", origRespNo);
        requestParamsBody.put("origTranType", "AP");
        System.out.println("requestParamsBody" + requestParamsBody);

        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("回执单请求头加签出现错误:{}", e.getMessage());
        }
        System.out.println("headers" + headersPost);
        String result = HttpRequest.get(requestUrl).addHeaders(headersPost).formStr(requestParamsBody).execute().body();
        log.info("招商回执单请求结果:{}", result);
        return result;
    }


    /**
     * 发送请求
     *
     * @param requestUrl
     * @param params
     */
    private static Map<String, String> sendRequest(String requestUrl, Map<String, Object> params) {
        log.info("cmb  request url: {}", requestUrl);
        try {
            String sign = createSign(params);
            Long currentTimeMills = System.currentTimeMillis() / 1000;
            String apiSignString = createApiSign(sign, Convert.toStr(currentTimeMills));
            log.info("CmbPayClient apiSignString: {}", apiSignString);
            Map<String, String> apiHeader = new HashMap<>();
            apiHeader.put("appid", CmbPayConfig.appid);
            apiHeader.put("timestamp", Convert.toStr(currentTimeMills));
            apiHeader.put("apisign", apiSignString);

            // 发送HTTP post请求
            Map<String, String> response = CmbUtils.postForEntity(requestUrl, sign, apiHeader);

            log.info("CmbPayClient sendRequest response: {}", response);

            return response;

        } catch (Exception e) {
            log.info("招商银行请求参数构建失败!");
        }
        return null;
    }


    static String createApiSign(String sign, String timestamp) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> signResultMap = mapper.readValue(sign, Map.class);
        // 组apiSign加密Map
        Map<String, String> apiSign = new TreeMap<>();
        apiSign.put("appid", CmbPayConfig.appid);
        apiSign.put("secret", CmbPayConfig.secret);
        apiSign.put("sign", signResultMap.get("sign").toString());
        apiSign.put("timestamp", timestamp);

        // MD5加密
        String MD5Content = SignatureUtil.getSignContent(apiSign);
        String apiSignString = MD5Utils.getMD5Content(MD5Content).toLowerCase();
        return apiSignString;
    }

    private static String createSign(Map<String, Object> transactionParams) throws JsonProcessingException {
        Map<String, String> requestPublicParams = new TreeMap<>();
        requestPublicParams.put("version", "0.0.1");    //版本号，固定为0.0.1(必传字段)
        requestPublicParams.put("encoding", "UTF-8");   //编码方式，固定为UTF-8(必传)
        requestPublicParams.put("signMethod", "02");   //签名方法，固定为02，表示签名方式为国密(必传)
        ObjectMapper mapper = new ObjectMapper();
        requestPublicParams.put("biz_content", mapper.writeValueAsString(transactionParams));
        String toSign = mapper.writeValueAsString(requestPublicParams);
        log.info("CmbPayClient generateSign 加签前的报文内容: {}", toSign);
        //对待加签内容进行排序拼接
        String signContent = SignatureUtil.getSignContent(requestPublicParams);
        //加签
        requestPublicParams.put("sign", SM2Util.sm2Sign(signContent, CmbPayConfig.secret_key));
        String requestStr = mapper.writeValueAsString(requestPublicParams);
        log.info("CmbPayClient generateSign 加签后的报文内容：{}", requestStr);
        return requestStr;

    }


    static Boolean checkSign(String content) {
        log.info("checkSign 要验签的报文内容：{} ", content);
        try {
            //验签
            ObjectMapper objectMapper = new ObjectMapper();
            Map<String, String> responseBodyMap = objectMapper.readValue(content, Map.class);
            String sign = responseBodyMap.remove("sign");
            String contentStr = SignatureUtil.getSignContent(responseBodyMap);
            boolean result = SM2Util.sm2Check(contentStr, sign, CmbPayConfig.public_key);
            return result;
        } catch (Exception e) {
            log.info("验签发生异常！");
            e.printStackTrace();
            return false;
        }
    }


    public static void refundListQry(String clearDate) {
        String requestUrl = "https://api.cmbchina.com/midsrv/ntsv2/refundListQry";
        CmbPayConfigEntity envConfig = getEnvConfig();
        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        Map<String, String> requestParamsBody = new HashMap<>();
        requestParamsBody.put("clearDate", clearDate);
        requestParamsBody.put("platformNo", envConfig.getMchId());
        System.out.println("requestParamsBody" + requestParamsBody);

        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("分账请求头加签出现错误:{}", e.getMessage());
        }
        System.out.println("headers" + headersPost);
        String result = HttpRequest.get(requestUrl).addHeaders(headersPost).formStr(requestParamsBody).execute().body();
        log.info("请求文件上传申请接口:{}", result);


    }

    private static CmbPayConfigEntity getEnvConfig() {
        String activeProfile = SpringUtil.getActiveProfile();
        CmbPayConfigEntity entity = new CmbPayConfigEntity();
        if ("prod".equals("prod")) {
            entity.setIsProd(Boolean.TRUE);
            entity.setRequestUrl("https://api.cmbchina.com");
            entity.setMchId(CmbPayConfig.mch_id);
            entity.setAppid(CmbPayConfig.appid);
            entity.setSecret(CmbPayConfig.secret);
            entity.setPublicKey(CmbPayConfig.public_key);
            entity.setSecretKey(CmbPayConfig.secret_key);
            entity.setSubMerId(CmbPayConfig.sub_mer_id);
            entity.setSubStoreId(CmbPayConfig.sub_store_id);
            entity.setUserId(CmbPayConfig.user_id);
        } else {
            entity.setRequestUrl("https://api.cmburl.cn:8065");
            entity.setMchId(CmbPayConfigTest.mch_id);
            entity.setAppid(CmbPayConfigTest.appid);
            entity.setSecret(CmbPayConfigTest.secret);
            entity.setPublicKey(CmbPayConfigTest.public_key);
            entity.setSecretKey(CmbPayConfigTest.secret_key);
            entity.setSubMerId(CmbPayConfigTest.sub_mer_id);
            entity.setSubStoreId(CmbPayConfigTest.sub_store_id);
            entity.setUserId(CmbPayConfigTest.user_id);
        }
        return entity;
    }


    /**
     * 公司体现
     *
     * @param tranAmt 提现金额
     * @param reqNo   提现编号
     */
    public static Map<String, Object> companyWithdraw(String tranAmt, String reqNo) {
        Console.log("提现");
        String requestUrl = "https://api.cmbchina.com/midsrv/ntsv2/withdraw";
        CmbPayConfigEntity envConfig = getEnvConfig();
        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        Map<String, String> requestParamsBody = new HashMap<>();
        requestParamsBody.put("reqNo", reqNo);
        requestParamsBody.put("mbrNo", envConfig.getSubStoreId());
        requestParamsBody.put("platformNo", envConfig.getMchId());
        requestParamsBody.put("tranAmt", tranAmt);
        requestParamsBody.put("wdwTyp", "1");
        Console.log("接口地址：{}", requestUrl);


        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("公司提现请求头加签出现错误:{}", e.getMessage());
        }
        Console.log("请求头：{}", JSON.toJSONString(headersPost));
        Console.log("请求体：{}", JSON.toJSONString(requestParamsBody));
        System.out.println("headers" + headersPost);
//        String result = HttpRequest.post(requestUrl).addHeaders(headersPost).formStr(requestParamsBody).execute().body();


        Map<String, Object> requestResult = HttpClient.request(requestUrl, HttpMethod.POST, headersPost, JSON.toJSONString(requestParamsBody), envConfig.getPublicKey());
        log.info("公司提现接口返回结果:{}", requestResult);
        return requestResult;
    }


    /**
     * 交易查询
     *
     * @param clearDate
     */
    public static void queryDeal(String origReqNo) {
        String requestUrl = "https://api.cmbchina.com/midsrv/ntsv2/itaTranQry";
        CmbPayConfigEntity envConfig = getEnvConfig();
        // POST 请求加签
        RequestConfig postRequestConfig = new RequestConfig.Builder().appId(envConfig.getAppid()).appSecret(envConfig.getSecret()).verify("SM3withSM2").version("0.1.0").privateKey(envConfig.getSecretKey()).build();
        Map<String, String> requestParamsBody = new HashMap<>();
        requestParamsBody.put("platformNo", envConfig.getMchId());
        requestParamsBody.put("origReqNo", origReqNo);
        requestParamsBody.put("origReqType", "WD");
        System.out.println("requestParamsBody" + requestParamsBody);

        String bizPostParams = JSON.toJSONString(requestParamsBody);
        Map<String, String> headersPost = null;
        try {
            headersPost = HttpClient.createHeaders(postRequestConfig, bizPostParams);
        } catch (Exception e) {
            log.error("交易查询请求头加签出现错误:{}", e.getMessage());
        }
        System.out.println("headers" + headersPost);
        String result = HttpRequest.get(requestUrl).addHeaders(headersPost).formStr(requestParamsBody).execute().body();
        log.info("交易查询接口结果:{}", result);


    }


    public static Map<String, String> queryOrderState(String orderNo) {
        String requestUrl = "https://api.cmbchina.com/ptn/api/weixinPay/orderStatusQuery";
        CmbPayConfigEntity envConfig = getEnvConfig();
        CmbRefundInfo cmbRefundInfo = new CmbRefundInfo();
        cmbRefundInfo.setOrderId(orderNo);
        cmbRefundInfo.setMerId(envConfig.getMchId());
        cmbRefundInfo.setUserId(envConfig.getUserId());
        Map<String, Object> params = BeanUtil.beanToMap(cmbRefundInfo, false, true);
        Map<String, String> refundResult = sendRequest(requestUrl, params);
        return refundResult;
    }

    public static Map<String, String> refundStatusQuery(String orderNo) {
        String requestUrl = "https://api.cmbchina.com/ptn/api/weixinPay/refundStatusQuery";
        CmbPayConfigEntity envConfig = getEnvConfig();
        CmbRefundInfo cmbRefundInfo = new CmbRefundInfo();
        cmbRefundInfo.setOrderId(orderNo);
        cmbRefundInfo.setMerId(envConfig.getMchId());
        cmbRefundInfo.setUserId(envConfig.getUserId());
        Map<String, Object> params = BeanUtil.beanToMap(cmbRefundInfo, false, true);
        Map<String, String> refundResult = sendRequest(requestUrl, params);
        return refundResult;
    }

}
